package com.zlx.sharelive.activity;

import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.HomeLableListBean;
import com.zlx.module_base.base_api.res_data.HomeSearchBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.NullTokenUtils;
import com.zlx.sharelive.utils.StringUt;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页搜索页面
 */
public class HomeSearchAc extends BaseAc {

    @BindView(R.id.rv_history_record)
    RecyclerView rv_history_record;
    @BindView(R.id.rv_popular_searches)
    RecyclerView rv_popular_searches;
    @BindView(R.id.et_search)
    EditText et_search;

    private int page = 1;
    private List<HomeLableListBean.InfoDTO> mList = new ArrayList<>();
    private CommonRecyclerViewAdapter<HomeLableListBean.InfoDTO> mAdapter;
    private List<HomeLableListBean.InfoDTO> mSaveList = new ArrayList<>();
    private CommonRecyclerViewAdapter<HomeLableListBean.InfoDTO> mSaveAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.ac_home_search;
    }

    @Override
    public void initViews() {
        super.initViews();

        if (null != SPUtil.getObjectFromShare(HomeSearchAc.this, Constants.SP_SAVE_LIST)) {
            mSaveList.addAll((Collection<? extends HomeLableListBean.InfoDTO>) SPUtil.getObjectFromShare(this, Constants.SP_SAVE_LIST));
        }

        initEditText();
        getHomeLableList();
        initRecyclerView1();
        initRecyclerView2();
    }

    private void initEditText() {
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND
                        || (event != null && event.getKeyCode() ==
                        KeyEvent.KEYCODE_ENTER)) {
                    return true;
                }
                return false;
            }
        });

        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    // 先隐藏键盘
                    HomeLableListBean.InfoDTO infoDTO = new HomeLableListBean.InfoDTO();
                    infoDTO.setLable(et_search.getText().toString().trim());
                    mSaveList.add(infoDTO);
                    List<HomeLableListBean.InfoDTO> list = new ArrayList<>();
                    list.addAll(mSaveList);
                    mSaveList.clear();
                    mSaveList.addAll(list);
                    mSaveAdapter.notifyDataSetChanged();
                    SPUtil.setObjectToShare(HomeSearchAc.this, mSaveList, Constants.SP_SAVE_LIST);

                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(HomeSearchAc.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    if (StringUt.isEmpty(et_search.getText().toString().trim())) {
                        Toast.makeText(HomeSearchAc.this, "搜索内容不可为空", Toast.LENGTH_SHORT).show();
                    } else {
                        homeSearch();
                    }
                }
                return false;
            }
        });
    }

    private void homeSearch() {
        ApiUtil.getHomeApi().homeSearch(String.valueOf(page),
                et_search.getText().toString().trim()).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<HomeSearchBean>>() {
            @Override
            public void onSuccess(ApiResponse<HomeSearchBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    if (data.getData().getInfo().get(0).getLongVideo().size() > 0 ||
                                            data.getData().getInfo().get(0).getShortVideo().size() > 0 ||
                                            data.getData().getInfo().get(0).getArticle().size() > 0) {
                                        startActivity(new Intent(HomeSearchAc.this, HomeSearchListAc.class)
                                                .putExtra("data", (Serializable) data.getData().getInfo().get(0))
                                                .putExtra("text", et_search.getText().toString().trim()));
                                    } else {
                                        Toast.makeText(HomeSearchAc.this, "没有搜索出结果", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Toast.makeText(HomeSearchAc.this, "没有搜索出结果", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    private void getHomeLableList() {
        ApiUtil.getHomeApi().getHomeLableList().observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<HomeLableListBean>>() {
            @Override
            public void onSuccess(ApiResponse<HomeLableListBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            mList.clear();
                            if (null != data) {
                                if (null != data.getData()) {
                                    if (data.getData().getCode() == 0) {
                                        if (null != data.getData().getInfo()) {
                                            mList.addAll(data.getData().getInfo());
                                        }
                                    }
                                }
                            }
                            mAdapter.notifyDataSetChanged();
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    /**
     * 初始化数据
     */
    private void initRecyclerView1() {
        //设置LayoutManager
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(this);
        //主轴为水平方向，起点在左端
        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
        //按正常方向换行
        flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);
        //定义项目在副轴轴上如何对齐
        flexboxLayoutManager.setAlignItems(AlignItems.CENTER);
        //多个轴对齐方式
        flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);
        rv_popular_searches.setLayoutManager(flexboxLayoutManager);

        mAdapter = new CommonRecyclerViewAdapter<HomeLableListBean.InfoDTO>(this, mList) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, HomeLableListBean.InfoDTO entity, int position) {
                holder.setText(R.id.tv_text, entity.getLable());
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_home_search;
            }
        };

        rv_popular_searches.setAdapter(mAdapter);

        mAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                et_search.setText(mList.get(position).getLable());
                homeSearch();
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initRecyclerView2() {
        //设置LayoutManager
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(this);
        //主轴为水平方向，起点在左端
        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
        //按正常方向换行
        flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);
        //定义项目在副轴轴上如何对齐
        flexboxLayoutManager.setAlignItems(AlignItems.CENTER);
        //多个轴对齐方式
        flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);
        rv_history_record.setLayoutManager(flexboxLayoutManager);

        mSaveAdapter = new CommonRecyclerViewAdapter<HomeLableListBean.InfoDTO>(this, mSaveList) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, HomeLableListBean.InfoDTO entity, int position) {
                holder.setText(R.id.tv_text, entity.getLable());
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_home_search;
            }
        };

        rv_history_record.setAdapter(mSaveAdapter);

        mSaveAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                et_search.setText(mSaveList.get(position).getLable());
                homeSearch();
            }
        });
    }


    @OnClick({R.id.tv_back, R.id.iv_remove, R.id.iv_delete})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_delete:
                mSaveList.clear();
                SPUtil.setObjectToShare(HomeSearchAc.this, mSaveList, Constants.SP_SAVE_LIST);
                mSaveAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_back:
                finish();
                break;
            case R.id.iv_remove:
                et_search.setText("");
                break;
        }
    }
}
